<script setup lang="ts">
	import { ref, provide, nextTick, unref, reactive } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { goodsCartListApi, goodsList } from '@/package_saleman/api/Order'
	import { addTransferMiddle, getTransMiddle } from '@/package_saleman/api/Home'
	import addGoodsPopup from './components/addGoodsPopup.vue'
	// import { getWarehouseApi } from '@/package_saleman/api/Home'
	// const wareHouseList = ref({});
	// const mainWareList = ref({})
	// const moveWareList = ref({})
	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const scrollTop = ref(0)
	const total_num = ref(0)

	interface RouteParams {
		start_warehouse_id : string
		warehouse_id : string
		end_warehouse_id : string
		transfer_type : '1' | '2'
	}
	const routeParams = ref<RouteParams>({
		start_warehouse_id: '',
		warehouse_id: '',
		end_warehouse_id: '',
		transfer_type: '1'
	})
	onLoad((options) => {

		routeParams.value = options as RouteParams
		goodsCart()
		nextTick(() => {
			paging.value?.reload()
		})
	})
	// const getWarehouse = async (id ?: any) => {
	// 	try {
	// 		const res = await getWarehouseApi(id);
	// 		mainWareList.value = res.data.filter(item => item.warehouse_type === 1).map(item => {
	// 			return {
	// 				...item,
	// 				label: item.name,
	// 				value: item.id
	// 			}
	// 		})
	// 		moveWareList.value = res.data.filter(item => item.warehouse_type === 2).map(item => {
	// 			return {
	// 				...item,
	// 				label: item.name,
	// 				value: item.id
	// 			}
	// 		})
	// 	} catch (error) {
	// 		console.error('获取仓库列表失败:', error);
	// 	}
	// }
	// getWarehouse()

	const useOrderDetail = () => {
		const shoplist = ref([])
		const goodsCart = async () => {
			const res = await goodsCartListApi()
			// 创建表示“全部”的元素
			let allItem = {
				id: 0,
				cate_name: "全部",
				children: [{
					id: 0,
					cate_name: '全部'
				}]
			}
			shoplist.value = res.data;
			shoplist.value.unshift(allItem)
		}

		return {
			shoplist,
			goodsCart
		}
	}
	const { shoplist, goodsCart } = useOrderDetail()
	const paging = ref<ZPagingInstance>()

	const useCURD = () => {
		const dataList = ref([])
		const query = ref({
			name: '',
			cate_id: ''
		})

		const getList : ZPagingEvent.Query = async (page, limit) => {
			const params = {
				...routeParams.value,
				...query.value,
				page,
				limit
			}
			try {
				const res = await goodsList(params)
				// total_num.value = res.data.total

				paging.value?.complete([...res.data.data])
				getCartList()
			} catch (err) {
				paging.value?.complete(false)
			}
		}

		const searchAction = () => {
			paging.value?.reload()
		}
		const getCartList = async () => {
			try {
				const params = {
					...routeParams.value,
				}
				const res = await getTransMiddle(params)
				const idToItem = new Map(dataList.value.map(item => [item.id, item]));

				res.data.forEach(({ goods: { id }, spec: { unit_name }, num }) => {
					const target = idToItem.get(id);
					if (target) {
						const combinedValue = [target.desc_cart, unit_name]
							.filter(Boolean)
							.join(',');
						if (!target.uniqueDescCarts) {
							target.uniqueDescCarts = new Map();
						}
						target.uniqueDescCarts.set(combinedValue, (target.uniqueDescCarts.get(combinedValue) || 0) + (num || 1));
						target.uniqueDescCartsArray = Array.from(target.uniqueDescCarts.entries())
							.map(([combinedValue, count]) => `${count}${combinedValue}`)
							.join(',');
					}
				});
				total_num.value = res.data.length || 0
			} catch (err) {
				paging.value?.complete(false)
			}
		}
		return {
			dataList,
			getList,
			query,
			searchAction,
			getCartList
		}
	}
	const { dataList, getList, query, searchAction, getCartList } = useCURD()

	const activeFirstLevel = ref(0)
	const active = ref(0)

	const switchFirstLevel = (index, children, id) => {
		activeFirstLevel.value = index
		active.value = 0
		if (index == 0) {
			query.value.name = ''
			query.value.cate_id = ''
			paging.value?.reload()
		} else {
			query.value.cate_id = children ? children[0].id : id
			paging.value?.reload()
		}
	}
	// 分类选择
	const changeNav = (index, id) => {
		active.value = index;
		if (id == 0) {
			query.value.name = ''
			query.value.cate_id = ''
			paging.value?.reload()
		} else {
			query.value.cate_id = id
			paging.value?.reload()
		}
	}

	const currentGoods = ref()
	const useGoodsPopup = () => {
		const showGoodsPopup = ref(false)

		const changeGoodsPopup = (state : boolean) => {
			showGoodsPopup.value = state
		}

		const cartList = ref([])
		const openGoodsPopup = (item) => {
			currentGoods.value = item
			changeGoodsPopup(true)
		}

		const addGoods = async (item) => {
			cartList.value = item
			if (unref(cartList).length === 0 || unref(cartList).every(({ num }) => num === 0)) {
				showNotify({
					type: 'error',
					message: '请添加商品！'
				})
				return false
			}
			await item.forEach(goodItem => {
				addTransferMiddle({ ...goodItem, ...unref(routeParams) })
			})

			// const params = {
			// 	...unref(routeParams),
			// 	detail: JSON.stringify(unref(cartList))
			// }
			// console.log(cartList.value, '2123')
			// try {
			// 	const res = await addTransferMiddle(params)
			// 	showNotify({
			// 		type: 'success',
			// 		message: res.msg
			// 	})
			// } catch (err) {
			// 	showNotify({
			// 		type: 'error',
			// 		message: err.msg
			// 	})
			// }
			changeGoodsPopup(false)
			paging.value?.reload()
		}

		return {
			showGoodsPopup,
			changeGoodsPopup,
			openGoodsPopup,
			addGoods,
			cartList
		}
	}
	const { showGoodsPopup, changeGoodsPopup, openGoodsPopup, addGoods, cartList } = useGoodsPopup()

	const submit = () => {
		// getCartList()
		setTimeout(() => uni.navigateBack({ delta: -1 }), 1000)
	}
	const goodShow = ref(false)
	const setGoodsList = reactive([])
	provide('currentGoods', currentGoods)
	// const typeShow = ref(true)
	// const wareHouse = ref(false)
	// const nextHouse = ref(false)
	// const typeColumns = reactive([
	// 	[
	// 		{
	// 			label: '车销提货',
	// 			value: 1
	// 		},
	// 		{
	// 			label: '车销回库',
	// 			value: 2
	// 		}
	// 	]
	// ]);
	// const chooseHouse = () => {
	// 	typeShow.value = false
	// 	wareHouse.value = true
	// }
	// const chooseNextHouse = () => {
	// 	wareHouse.value = false
	// 	nextHouse.value = true
	// }
</script>
<template>
	<z-paging ref="paging" v-model="dataList" @query="getList" :auto="false">
		<template #top>
			<view class="header">
				<up-navbar title="商城列表" autoBack :fixed="false"></up-navbar>
				<view class="search-area">
					<up-search v-model="query.name" @search="searchAction" @custom="searchAction" @clear="searchAction"
						showAction actionText="搜索" animation shape="square"
						bgColor="rgba(243, 242, 245, 1)"></up-search>
				</view>
				<view>
					<!-- 一级分类 -->
					<scroll-view class="first-level" scroll-x>
						<view v-for="(category, index) in shoplist" :key="index" class="category-item"
							:class="{ 'active': index === activeFirstLevel }"
							@tap="switchFirstLevel(index, category.children, category.id)">
							{{ category.cate_name }}
						</view>
					</scroll-view>
				</view>
			</view>
		</template>
		<template #left>
			<!-- 二级分类 -->
			<view class="classification">
				<scroll-view class="bg" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true">
					<block v-for="(item,ins) in shoplist[activeFirstLevel]?.children" :key="ins">
						<view class="nav-item" :class="{'ac':active == ins}" @click="changeNav(ins,item.id)">
							{{ item.cate_name}}
						</view>
					</block>
				</scroll-view>
			</view>
		</template>
		<view class="goods-item" v-for="(item,index) in dataList" :key="index" @click="openGoodsPopup(item)">
			<view class="goods-img">
				<up-image :show-loading="true" :src="item.img" width="152rpx" height="152rpx"></up-image>
			</view>
			<view class="goods-info">
				<view class="line">
					<up-text :text="item?.goods_name" lines="2" bold color="rgba(39, 38, 41, 1)" size="28rpx"></up-text>
				</view>
				<!-- <view class="line">
					<text class="label">选中{{item.cart_desc}}</text>
				</view> -->
				<view class="line">
					<text class="label">选中 {{item.uniqueDescCartsArray}}</text>
				</view>
				<view class="line">
					<span style="color: #F54E4E;font-size: 28rpx;" v-for="(detailItem,index) in item.spec"
						:key="detailItem.id">
						{{ '￥' + detailItem.sale_price + ','}}
					</span>
					<!-- <up-text :text="item.spec_price" color="#F54E4E" size="28rpx"></up-text> -->
				</view>
			</view>
		</view>
		<template #bottom>
			<view class="submit-area">
				<view class="info">
					<view class="line">
						<view class="label">共<text style="color: #F54E4E;">{{total_num}}</text>件</view>
					</view>
				</view>
				<view class="submit-btn">
					<up-button text="返回" shape="circle" color="rgba(55, 131, 252, 1)" @click="submit"></up-button>
				</view>
				<addGoodsPopup :show="showGoodsPopup" @close="changeGoodsPopup" @submit="addGoods"></addGoodsPopup>
				<up-notify ref="NotifyRef"></up-notify>
			</view>
		</template>
	</z-paging>
	<!-- <up-popup :show="typeShow" :columns="typeColumns" keyName="label" @cancel="typeShow=false" @confirm="chooseHouse"></up-popup>
	<up-popup :show="wareHouse" :columns="mainWareList" keyName="label" @cancel="wareHouse=false" @confirm="chooseNextHouse"></up-popup>
	<up-popup :show="nextHouse" :columns="moveWareList" keyName="label" @cancel="nextHouse=false"></up-popup> -->
</template>

<style scoped lang="scss">
	.header {
		.search-area {
			display: flex;
			align-items: center;
			width: calc(100% - 50rpx);
			height: 100rpx;
			margin: 30rpx 15rpx;
			padding: 0 15rpx;
			border-radius: 20rpx;
			background: rgba(243, 242, 245, 1);
			box-sizing: border-box;
		}

		.first-level {
			width: 100%;
			white-space: nowrap;
			overflow-x: auto;
			padding: 10rpx;
			box-sizing: border-box;

			.category-item {
				padding: 20rpx;
				cursor: pointer;
				white-space: nowrap;
				display: inline-block;
			}

			.category-item.active {
				font-size: 24rpx;
				border-radius: 8rpx;
				background-color: #f0f0f0;
			}
		}
	}

	.classification {
		// /* 设置宽度 */
		width: 200rpx;
		height: calc(100vh - 400rpx);
		overflow-y: scroll;
		background: #F7F8F9;
		margin-right: 10rpx;

		.bg {
			display: block;

			/* 如果二级分类内容过多，显示滚动条 */
			.nav-item {
				width: 200rpx;
				height: 104rpx;
				line-height: 104rpx;
				background: #F7F8F9;
				font-size: 24rpx;
				color: #505660;
				text-align: center;
			}

			.ac {
				background: #fff;
				color: rgba(55, 131, 252, 1);
			}

		}
	}



	.goods-item {
		display: flex;
		gap: 20rpx;
		width: 100%;
		height: 240rpx;
		padding: 30rpx;
		box-sizing: border-box;

		.goods-img {
			width: 152rpx;
			flex-shrink: 0;
		}

		.goods-info {
			position: relative;
			flex: auto;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			padding: 12rpx 0;

			.line {
				display: flex;
				align-items: center;
				gap: 6rpx;
				font-weight: 500;

				.label {
					color: rgba(55, 131, 252, 1);
					font-size: 24rpx;
				}
			}

			.price {
				align-items: flex-end;
			}

			.btn-wrap {
				position: relative;
			}
		}

	}

	.submit-area {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: calc(100% - 80rpx);
		height: 100rpx;
		background-color: #FFF;
		padding: 0 40rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS 11.2及以上 */
		box-shadow: 0rpx -4rpx 8rpx 0rpx #efefef;

		.info {
			flex: 2;
			display: flex;
			flex-direction: column;

			.line {
				display: flex;
				gap: 12rpx;
				color: #9C9AA1;
			}

			.label {
				font-size: 28rpx;
			}
		}

		.submit-btn {
			flex: 1;
		}
	}
</style>